package rabbit.common;


import com.sun.org.apache.xml.internal.serialize.XMLSerializer;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Stream;

/**
 * Created by root on 17-4-9.
 */
@XmlType(name = "rabbiMqConfigs")
@XmlRootElement(name = "rabbitMqConfigs")
public class rabbitMqConfigBundle {

    private static rabbitMqConfigBundle _instance;
    private static Lock lock = new ReentrantLock();


    public static rabbitMqConfigBundle getConfigBundle(){
        try{
            lock.lock();
            if(rabbitMqConfigBundle._instance==null) {
                rabbitMqConfigBundle._instance = XmlSerializerHelper.deserialize(rabbitMqConfigBundle.class,rabbitMqPropertiesHelper.getInstance().getConfigPath());
                rabbitMqConfigBundle._instance.reloadConfig();
            }
            return rabbitMqConfigBundle._instance;
        }
        finally {
            lock.unlock();
        }
    }

    private ArrayList<rabbitMqConfig> configs;


    private HashMap<String,rabbitMqConfig> configMap;


    public rabbitMqConfigBundle(){
        reloadConfig();
    }

    public void reloadConfig(){
        this.configMap = new HashMap<String, rabbitMqConfig>();
        if(this.configs!=null){
            this.configs.forEach(item->this.configMap.put(item.getId(),item));
        }
    }

    @XmlElement(name = "config")
    public ArrayList<rabbitMqConfig> getConfigs() {
        return configs;
    }

    public void setConfigs(ArrayList<rabbitMqConfig> configs) {
        this.configs = configs;
    }


    public HashMap<String,rabbitMqConfig>  getConfigMap(){

        return this.configMap;
    }
}
